package com.netty.decoder.protocol;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/**
 * @author xl-9527
 * @since 2025/8/9
 **/
public class HttpServer {

    private static final Logger log = LoggerFactory.getLogger(HttpServer.class);

    public void run() throws InterruptedException {
        final ServerBootstrap bootstrap = new ServerBootstrap()
                .group(new NioEventLoopGroup(), new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(final NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HttpServerCodec())
                                .addLast(new LoggingHandler())
                                .addLast(new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
                                        super.channelRead(ctx, msg);
                                    }
                                })
                                .addLast(new SimpleChannelInboundHandler<HttpRequest>() {
                                    @Override
                                    protected void channelRead0(final ChannelHandlerContext ctx, final HttpRequest msg) throws Exception {
                                        log.info("读到数据：{}", msg.uri());
                                        final DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
                                        final byte[] bytes = "<h1>你好</h1>".getBytes();
                                        response.headers().add(HttpHeaderNames.CONTENT_LENGTH, bytes.length);
                                        response.headers().add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_HTML);
                                        response.content().writeBytes(bytes);
                                        ctx.writeAndFlush(response);
                                    }
                                });
                    }
                });

        // bind
        bootstrap.bind(8080).sync();
    }
}
